<template>
  <div>
    <div v-if="progressTextVisible">
      <span>{{progressText}}</span>
      <span style="float: right">{{`${progressPercentage}%`}}</span>
    </div>
    <vue-countdown v-else v-slot="{days, hours, minutes}" :time="sendDistanceTime" @end="onCountdownEnd">
      <span class="el-icon-timer">{{`${days && days + '天' || ''}${hours && hours + '时' || ''}${minutes}分后发送`}}</span>
    </vue-countdown>
    <el-progress
      :show-text="false"
      color="#53a8ff"
      :percentage="progressPercentage"
    />
  </div>
</template>

<script>
import moment from 'moment';
import VueCountdown from '@chenfengyuan/vue-countdown';

export default {
  components: {
    VueCountdown
  },
  props: {
    row: Object
  },
  data() {
    return {
      countdownEnd: false,
    };
  },
  computed: {
    progressTextVisible() {
      return this.row.sendTotal || !this.row.isvalid || this.countdownEnd;
    },
    progressPercentage() {
      let { row } = this;
      return row.sendTotal ? Math.floor(row.successTotal / row.sendTotal * 100) : 0;
    },
    progressText() {
      let { row } = this;
      return row.sendTotal ? `${row.successTotal} / ${row.sendTotal}` : '0 / 0';
    },
    // 对于还未发送的，返回距离第一次发送时间
    sendDistanceTime() {
      let { row } = this;
      let timedTime; // 首次发送日期时间
      // 如果是非重复（立即发送）
      if (row.sendMode == 1) {
        timedTime = moment(row.weekTime, 'HH:mm');
      } else {
        let createAt = moment(row.createTime.substring(0, 16));        // 定时的创建时间
        let createAtWeekday = (createAt.weekday() == 0 ? 7 : createAt.weekday()); // 定时的创建时间于周几
        // 如果是重复发送，找到距离现在最近的日期
        let wes = row.weekDay.split('');
        // 这里7表示周日
        let weekday = wes.slice(1, 7).concat(wes[0]).indexOf('1') + 1;
        // 如果周几小于当前周几，则weekday是作为下周几处理
        let [h, m] = row.weekTime.split(':');
        let baseTimedTime = moment(row.createTime.substring(0, 10), 'YYYY-MM-DD').hour(h).minute(m);
        if ((weekday < createAtWeekday) || baseTimedTime.isBefore(createAt)) {
          baseTimedTime.add(7 - createAtWeekday + weekday, 'day');
        } else {
          baseTimedTime.weekday(weekday);
        }
        timedTime = baseTimedTime;
      }
      
      return (timedTime.unix() - moment().unix()) * 1000;
    }
  },
  methods: {
    onCountdownEnd() {
      this.countdownEnd = true;
    }
  },
}
</script>